//部署好的合约地址
var commentRegistryAddress = "0xcfeb869f69431e42cdb54a4f4f105c19c080a601";
var currentAddress;

var defaultGas = 4700000;

//登录账户
function login(){
    logAddress=$("#loginAddress").val();
    $("#loginAddress").html("");
    CommentAccount.at(logAddress).then( function(instance){
        currentAddress=logAddress;
        getAccountInfo();
    }).catch( err => {console.log("LogIn ERROR:"+err);window.alert("LogIn ERROR:"+err)})
}

// 注册评课社区账号
function register() {
    var commentRegistryInstance;
    var name = $("#accountName").val();
    var commentAccountAddress;
    CommentAccount.new({from: web3.eth.accounts[0], gas: defaultGas}).then(function (instance) {
        commentAccountAddress = instance.address;
        currentAddress = commentAccountAddress;
        $("#accountAddress").val(commentAccountAddress);
    }).then(function () {
        CommentRegistry.at(commentRegistryAddress).then(function (instance) {
            commentRegistryInstance = instance;
            return commentRegistryInstance.register(name, commentAccountAddress, {
                from: web3.eth.accounts[0],
                gas: defaultGas
            });
        }).then(function (txReceipt) {
            console.info(txReceipt);
            showAllRegister();
        });
    });
}

//通过用户id得到他的{id,名字,地址}
function getRegisterUser(id) {
    var addr;
    return CommentRegistry.at(commentRegistryAddress).then(function (instance) {
        commentRegistryInstance = instance;
        return commentRegistryInstance.getAddressOfId.call(id).then(function (a) {
            addr = a;
            return commentRegistryInstance.getNameOfAddress.call(addr);
        }).then(function (name) {
            return {id: id, name: name, addr: addr}
        })
    });
}

// 得到评课社区平台上所有注册用户的数量
function getTotalRegisterUser() {
    return CommentRegistry.at(commentRegistryAddress).then(function (instance) {
        commentRegistryInstance = instance;
        return commentRegistryInstance.getNumberOfAccounts.call();
    }).then(function (total) {
        return total;
    });
}

//查看平台所有已注册的微博账户
// {id:1,name:"",address:""}
async function getAllRegister() {
    let users = [];
    let total = await getTotalRegisterUser();
    for (let i = 0; i < total; i++) {
        let user = await getRegisterUser(i);
        users.push(user);
    }
    return users;

}

// 在页面中展示所有已注册用户
function showAllRegister() {
    getAllRegister().then(function (list) {
        $("#accountList").html('');
        list.forEach(function (item, index) {
            $("#accountList").append("<tr><td>" + item.id + "</td><td>" + item.name + "</td><td>" + item.addr + "</td></tr>");
        });
        currentAddress = list[0].addr || "";
    })
}

// 平台余额
function plantformBalance() {
    let balance = web3.eth.getBalance(commentRegistryAddress);
    balance = web3.fromWei(balance, 'ether');
    return balance.toString();
}

// 平台基本信息
function getPlantformInfo() {
    $("#plantformAccount").html(commentRegistryAddress);
    $("#plantformBalance").html(plantformBalance() + " ether");
}


// 账户发评价
function sendComment() {
    var commentAccountInstance;
    var commentRegistryInstance;
    var classname = $("#classNameToComment").val();
    var commentContent = $("#commentContent").val();
    CommentAccount.at(currentAddress).then(function (instance) {
        commentAccountInstance = instance;
        return commentAccountInstance.comment(classname, commentContent, {from: web3.eth.accounts[0], gas: defaultGas});
    }).then(function (txReceipt) {
        console.info(txReceipt);
        CommentRegistry.at(commentRegistryAddress).then(function (instance) {
            commentRegistryInstance = instance;
            return commentRegistryInstance.addComment(classname, currentAddress, {
                from: web3.eth.accounts[0],
                gas: defaultGas
            });
        }).then(function (txReceipt) {
            console.info(txReceipt);
        });
    }).then(function () {
        $("#classNameToComment").val('');
        $("#commentContent").val('');
        showComment();
    });
}

// 返回accountAddress账户发出的第id条评价
function getComment(accountAddress, id) {
    var commentAccountInstance;
    return CommentAccount.at(accountAddress).then(function (instance) {
        commentAccountInstance = instance;
        return commentAccountInstance.getCommentById.call(id).then(function (w) {
            return {id: id, commentContent: w[0], timestamp: w[1]};
        })
    });
}

// 返回账户发的评价总数
function getTotalComment(accountAddress) {
    var commentAccountInstance;
    return CommentAccount.at(accountAddress).then(function (instance) {
        commentAccountInstance = instance;
        return commentAccountInstance.getNumberOfComments.call();
    }).then(function (total) {
        return total;
    });
}

// 返回账户发的所有评价
async function getAllComment(accountAddress) {
    let comments = [];
    let total = await getTotalComment(accountAddress);
    for (let i = 0; i < total; i++) {
        let comment = await getComment(accountAddress, i);
        comments.push(comment)
    }
    return comments;
}

// 在页面中展示评论信息
function showComment() {
    getAllComment(currentAddress).then(function (list) {
        $("#myContentList").html('');
        list.forEach(function (item, index) {
            $("#myContentList").append("<tr><td>" + item.id + "</td><td>" + item.commentContent + "</td><td>" + item.timestamp + "</td></tr>");
        });
    });
}


// 账户余额
function accountBalance() {
    var balance = web3.eth.getBalance(currentAddress);
    balance = web3.fromWei(balance, 'ether');
    return balance.toString();
}

function getNameOfAddress(accountAddress) {
    var commentRegistryInstance;
    return CommentRegistry.at(commentRegistryAddress).then(function (instance) {
        commentRegistryInstance = instance;
        return commentRegistryInstance.getNameOfAddress.call(accountAddress);
    }).then(function (name) {
        return name;
    });
}

async function getAccountInfo() {
    var name = await getNameOfAddress(currentAddress);
    $("#myName").html(name);
    $("#myAccount").html(currentAddress);
    $("#myBalance").html(accountBalance() + " ether");
}

//返回账户accountAddress对课程classname的评价
function getCommentByClass(accountAddress,classname){
    var commentAccountInstance;
    return CommentAccount.at(accountAddress).then(function (instance) {
        commentAccountInstance = instance;
        return commentAccountInstance.getCommentByClass.call(classname).then(function (w) {
            return w;
        })
    });
}

//得到有评价过查询课程的用户地址列表
function getSearchAccountList(classname){
    var commentRegistryInstance;
    return CommentRegistry.at(commentRegistryAddress).then(function (instance) {
        commentRegistryInstance = instance;
        return commentRegistryInstance.getAddressArray.call(classname);
    }).then(function (addrList) {
        return addrList;
    });
}

//返回查询课程的所有评价
async function getAllSearchComment(classname){
    let comments = [];
    let addrList = await getSearchAccountList(classname);
    for (let i = 0; i < addrList.length; i++) {
        let comment = await getCommentByClass(addrList[i], classname);
        let accountName = await getNameOfAddress(addrList[i]);
        comments.push({name: accountName, commentContent: comment[0], timestamp: comment[1]});
    }
    return comments;
}

//搜索课程对应的评价内容并显示
function showSearchComment(){
    var classname = $("#searchClassName").val();
    getAllSearchComment(classname).then(function (list) {
        $("#classCommentList").html('');
        list.forEach(function (item, index) {
            $("#classCommentList").append("<tr><td>" + item.name + "</td><td>" + item.commentContent + "</td><td>" + item.timestamp + "</td></tr>");
        });
    });  
}

//得到可评价课程的总数
function getTotalClass() {
    var commentRegistryInstance;
    return CommentRegistry.at(commentRegistryAddress).then(function(instance){
        commentRegistryInstance = instance;
        return commentRegistryInstance.getNumberOfClass.call();
    }).then(function (total){
        return total;
    })
}
//得到第id条课程名
function getClassNameById(id){
    var commentRegistryInstance;
    return CommentRegistry.at(commentRegistryAddress).then(function(instance){
        commentRegistryInstance=instance;
        return commentRegistryInstance.getClassNameById.call(id);
    }).then(function(name){
        return name;
    })
}

//得到所有可评价的课程名
async function getAllClass(){
    let classList=[];
    let total = await getTotalClass();
    for(let i=0;i<total;i++){
        let name= await getClassNameById(i);
        classList.push({id:i, classname:name});
    }
    return classList;
}

//在页面上显示当前可评价课程名
function showAllClass(){
    getAllClass().then(function (list) {
        $("#classList").html('');
        list.forEach(function (item, index) {
            $("#classList").append("<tr><td>" + item.id + "</td><td>" + item.classname + "</td></tr>");
        });
    });  
}

//添加课程至可评价课程列表
function addClass(){
    var addClassName = $("#addClassName").val();
    var commentRegistryInstance;
    CommentRegistry.at(commentRegistryAddress).then(function (instance) {
        commentRegistryInstance = instance;
        return commentRegistryInstance.addClass(addClassName, {
            from: web3.eth.accounts[0],
            gas: defaultGas
        })
    }).then(function (txReceipt) {
        console.info(txReceipt);
        showAllClass();
    });   
}
window.onload = function () {

    getPlantformInfo();
    showAllRegister();

    $("#home_tab").click(function (e) {
        e.preventDefault();
        getPlantformInfo();
        showAllRegister();
    })

    $("#account_tab").click(function (e) {
        e.preventDefault();
        getAccountInfo();
        showComment();
    })

    $("#class_tab").click(function (e) {
        e.preventDefault();
    })
    $("#admin_tab").click(function (e) {
        e.preventDefault();
        showAllClass();
    })

    $("#registerBtn").click(function () {
        register();
    });

    $("#sendCommentBtn").click(function () {
        sendComment();
    });

    $("#searchBtn").click(function () {
        showSearchComment();
    });

    $("#addClassBtn").click(function () {
        addClass();  
    });
    $("#loginBtn").click(function () {
        login();  
    });

};
